"""
使用进程池
"""

import os
import time
import random

from multiprocessing import Pool


def do_long_time_task(name):
    print("进程任务 {name}（{pid}）".format(name=name, pid=os.getpid()))
    start_time = time.time()
    time.sleep(random.random() * 3)
    end_time = time.time()
    print("执行进程任务 {name} 耗时 {cost_time} 秒 ".format(name=name, cost_time='%.2f' % (end_time - start_time)))


def do_task():
    print("父进程 {parent_pid}".format(parent_pid=os.getpid()))
    # Pool的默认大小是CPU的核数
    p = Pool(4)
    for i in range(7):
        p.apply_async(do_long_time_task, args=(i,))
    print("等待所有子线程执行完...")
    # 关闭进程池（不允许再添加新的进程）
    p.close()
    p.join()
    print("所有子线程执行完毕")


if __name__ == "__main__":
    do_task()
